home *** CD-ROM | disk | FTP | other *** search
/ Collection of Tools & Utilities / Collection of Tools and Utilities.iso / basic / wh_rand.zip / WH_RAND.BAS < prev   
BASIC Source File  |  1992-01-13  |  2KB  |  56 lines

  1. ' RAND  ■  Sample Code in QB 4.5 by Luigi M. Bianchi ■  January 13, 1992
  2. '
  3. ' RAND generates random numbers between 0 and 1.
  4. ' RAND uses the Wichmann-Hill algorithm (cf. BYTE, March 1987, p.127).
  5. '
  6. ' The main module MUST initialize the random number generator, either
  7. ' with q=RAND(0.), for repeatable sequences, or with q=RAND(-1.), for
  8. ' randomized sequences, where q is a double-precision dummy variable.
  9. ' To generate random integers between a and b (a<b) use the expression
  10. ' INT((b-a+1)*RAND(1)+a).
  11. '
  12. ' A similar declaration must be used in the main module.
  13. '
  14. DECLARE FUNCTION RAND (q AS DOUBLE)
  15. END
  16.  
  17. ' Initializations:
  18. '
  19. ' q=RAND(0.)  starts the generator with seeds 1,10000,3000 (cf. op. cit.)
  20. ' q=RAND(-1.) randomizes (reseeds) the generator
  21. ' q=RAND(1.)  returns a random number (double precision) between 0 and 1
  22. '
  23. FUNCTION RAND (q AS DOUBLE) STATIC
  24. '
  25. DEFINT L-M    ' the seeds are 16-bit integers
  26. DEFDBL Q-T    ' while the dummy & temp variables, and RAND are 64-bit doubles
  27. '
  28. IF q = 0. THEN ' if repeatable sequences
  29.    L = 1: M = 10000: N = 3000
  30.    EXIT FUNCTION    ' to ensure that only initialization is carried out
  31. '
  32. ELSEIF q < 0. THEN    ' if randomized sequences
  33.    RANDOMIZE TIMER
  34.    L = INT(30000 * RND) + 1
  35.    M = INT(30000 * RND) + 1
  36.    N = INT(30000 * RND) + 1
  37.    EXIT FUNCTION    ' to ensure that only initialization is carried out
  38. '
  39. END IF
  40. '
  41. '  Wichmann-Hill Algorithm
  42. '
  43. L = 171 * (L MOD 177) - (L \ 177) * 2
  44. IF L < 0 THEN L = L + 30269
  45. M = 172 * (M MOD 176) - (M \ 176) * 35
  46. IF M < 0 THEN M = M + 30307
  47. N = 170 * (N MOD 178) - (N \ 178) * 63
  48. IF N < 0 THEN N = N + 30323
  49. temp = L / 30269 + M / 30307 + N / 30323
  50. RAND = temp - INT(temp)
  51. '
  52. END FUNCTION
  53.  
  54.  ■  Luigi M. Bianchi ■  CIS 72060,3723
  55.  
  56.